#include "ThreadPool.h"
#include <iostream>
#include "../utils/util.h"

using namespace std;

namespace PFS
{
    ThreadPool::ThreadPool(thread_fun fun)
        : init_num(10)
    {
        init_data(init_num, fun);
    }

    ThreadPool::ThreadPool(int num, thread_fun fun)
        :init_num(num)
    {
        init_data(init_num, fun);
    }

    ThreadPool::~ThreadPool()
    {
        size_t len = thread_list.size();
        size_t i = 0;
        for(; i < len; i++)
        {
            thread_list[i]->detach();
            thread_list[i]->join();
        }
    }

    void ThreadPool::init_data(int num, thread_fun fun)
    {
        used = -1;
        thread_list.clear();

        for(int i = 0; i < init_num; i++)
        {
            WorkerThread *thread = new EventThread(fun);
            thread_list.push_back(thread);
            thread->run();
        }
        func = fun;
    }

    void ThreadPool::stop()
    {
        size_t len = thread_list.size();
        for(int i = 0; i < len; i++)
            thread_list[i]->exit();
    }
    void ThreadPool::set_task(Job* job, void *data)
    {
        int id = atomic_add_return(used) % init_num;//cycle distribute the workerthread to work
        EventThread* tmp_thread = thread_list[id];
        tmp_thread->set_task(job, data);//push it to queue which will trigger the event to pop it, and deal 
    }
}

